package com.hnhp.advice;

import cn.hutool.json.JSONUtil;
import com.hnhp.dto.ResponseDTO;
import com.hnhp.exception.BizException;
import com.hnhp.info.PageInfo;
import com.hnhp.threadlocal.LocalPageInfoUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

// 针对controller做的一个增强类型
@RestControllerAdvice
public class MyResponseAdivce implements ResponseBodyAdvice<Object> {

    // 默认是不增强任何方法
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }
    @ExceptionHandler
    public Object processException(Exception ex){
        if (ex instanceof BizException){
            BizException bizException=(BizException) ex;
            return ResponseDTO.error(bizException.getCode(),ex.getMessage());
        }
//        ResponseDTO dto =ResponseDTO.error(1,ex.getMessage());
        return ResponseDTO.error(808,ex.getMessage());
    }

    @Override
    public Object beforeBodyWrite(
            Object body,
            MethodParameter methodParameter,
            MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
            ServerHttpRequest serverHttpRequest,
            ServerHttpResponse serverHttpResponse) {
        if (body instanceof ResponseDTO){
            return body;
        }
        ResponseDTO dto=ResponseDTO.success(body);
        PageInfo pageInfo= LocalPageInfoUtil.get();
        if (pageInfo != null){
            Map<Object,Object> map = new HashMap<>();
            map.put("total",pageInfo.getTotal());
            map.put("items",body);
            dto=ResponseDTO.success(map);
            LocalPageInfoUtil.remove();
        }
        //强转为json数据
        if(aClass==StringHttpMessageConverter.class){
            //强制转换为JSON字符串
            return JSONUtil.toJsonStr(dto);
        }

        return dto;
    }
}
